package com.app.adapter.recycler.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.utils.CommonUtil;
import com.app.utils.OptionImageUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.text.MessageFormat;

public class ViewHolder extends RecyclerView.ViewHolder
{
    private SparseArray<View> mViews;
    private View mConvertView;
    private Context mContext;

    public ViewHolder(Context context, View itemView)
    {
        super(itemView);
        mContext = context;
        mConvertView = itemView;
        mViews = new SparseArray<View>();
    }


    public static ViewHolder createViewHolder(Context context, View itemView)
    {
        ViewHolder holder = new ViewHolder(context, itemView);
        return holder;
    }

    public static ViewHolder createViewHolder(Context context,
                                              ViewGroup parent, int layoutId)
    {
        View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
                false);
        ViewHolder holder = new ViewHolder(context, itemView);
        return holder;
    }

    /**
     * 通过viewId获取控件
     *
     * @param viewId
     * @return
     */
    public <T extends View> T getView(int viewId)
    {
        View view = mViews.get(viewId);
        if (view == null)
        {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public View getConvertView()
    {
        return mConvertView;
    }




    /****以下为辅助方法*****/

    /**
     * 这个方法是特殊方法 现在进行添加 rating_bar
     */
    public ViewHolder setStar(int viewId, float stars)
    {
        com.app.view.RatingBar ratingBar = getView(viewId);
        if(stars >0){
            stars = stars/2;
        }
        ratingBar.setStar(stars);//设置显示的星星个数
        return this;
    }

    /**
     * 设置TextView的值
     *
     * @param viewId
     * @param text
     * @return
     */
    public ViewHolder setText(int viewId, String text)
    {
        TextView tv = getView(viewId);
        String str = (text == null) ?"":text.toString();
        tv.setText(str);
       return this;
    }

    /**
     * 设置文字限制行数
     * @param viewId
     * @param line
     * @return
     */
    public ViewHolder setTextLine(int viewId, int line)
    {
        TextView tv = getView(viewId);
        tv.setLines(line);
        tv.setEllipsize(TextUtils.TruncateAt.END);
        return this;
    }

    public ViewHolder setTextReplace(int viewId,int resID, String text)
    {
        TextView tv = getView(viewId);
        String str = (text == null) ?"":text.toString();
        if(resID >0)
            str = MessageFormat.format(QXApplication.getContext().getResources().getString(resID),text);
        tv.setText(str);
        return this;
    }

    public ViewHolder setHintText(int viewId, String text)
    {
        TextView tv = getView(viewId);
        String str = (text == null) ?"":text.toString();
        tv.setHint(str);
        return this;
    }

    public ViewHolder setLines(int viewId, int line)
    {
        TextView tv = getView(viewId);
        tv.setMaxLines(line);

        return this;
    }

    public ViewHolder setLength(int viewId, int line)
    {
        TextView tv = getView(viewId);
        tv.setFilters(new InputFilter[] { new InputFilter.LengthFilter(line) });
        return this;
    }

    public ViewHolder setTextBufferType(int viewId, SpannableString spannable)
    {
        TextView tv = getView(viewId);
        tv.setText(spannable);
        return this;
    }

    //改变背景
    public ViewHolder setTextDrawSolid(int viewId, String color)
    {
        TextView tv = getView(viewId);
        GradientDrawable background = (GradientDrawable) tv.getBackground();
        background.setColor(Color.parseColor(color));
        return this;
    }

    public ViewHolder setTextDrawStroke(int viewId, String color)
    {
        TextView tv = getView(viewId);
        GradientDrawable background = (GradientDrawable) tv.getBackground();
        background.setStroke(CommonUtil.dip2px(QXApplication.getContext(),1),Color.parseColor(color));
        return this;
    }

    /**
     * HTML 封装
     * @param viewId
     * @param text
     * @return
     */
    public ViewHolder setTextHTMLTwo(int viewId, String text)
    {
        TextView tv = getView(viewId);
        String str = (text == null) ?"":text.toString();
        Spanned fromHtml = Html.fromHtml(str);
        tv.setText(fromHtml);
        return this;
    }
    /**
     * HTML 封装
     * @param viewId
     * @param text
     * @return
     */
    public ViewHolder setTextHTML(int viewId, String text)
    {
        TextView tv = getView(viewId);
        String str = (text == null) ?"":text.toString();
        Spanned fromHtml = Html.fromHtml(str);
        String endStr = deleeEmpty(fromHtml.toString());
        tv.setText(endStr);
        return this;
    }

    public ViewHolder setPadding(int viewId, int left,int top,int right,int bottom)
    {
        View view = getView(viewId);
        view.setPadding(left, top, right, bottom);
        return this;
    }

    private String deleeEmpty(String str){
        String temp = str;
        if(str.isEmpty())
            return temp;
        if(str.endsWith("\n\n")){
            temp = str.substring(0,(str.length() - 2));
        }
        return temp;
    }

    public ViewHolder setText(int viewId, int resId){
        TextView tv = getView(viewId);
        tv.setText(resId);
        return this;
    }

    public ViewHolder setTextColor(int viewId, String color){
        TextView tv = getView(viewId);
        if(null != color && color.length() == 7){
            tv.setTextColor(Color.parseColor(color));
        }
        return this;
    }

    public ViewHolder setSelect(int viewId,boolean isSelect){
        View view = getView(viewId);
        view.setSelected(isSelect);
        return this;
    }

    public ViewHolder setTextDrawableTop(int viewId, int id)
    {
        TextView tv = getView(viewId);
        Drawable drawable = null;
        drawable = mContext.getResources().getDrawable(id);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        tv.setCompoundDrawables(null,drawable,null, null);
        return this;
    }

    public ViewHolder setTextDrawableLeft(int viewId, int id)
    {
        TextView tv = getView(viewId);
        Drawable drawable = null;
        drawable = mContext.getResources().getDrawable(id);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        tv.setCompoundDrawables(drawable,null,null, null);
        return this;
    }

    public ViewHolder setTextDrawableRight(int viewId, int id)
    {
        TextView tv = getView(viewId);
        Drawable drawable = null;
        drawable = mContext.getResources().getDrawable(id);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        tv.setCompoundDrawables(null,null,drawable, null);
        return this;
    }

    public ViewHolder setImageResource(int viewId, int resId)
    {
        ImageView view = getView(viewId);
        view.setImageResource(resId);
        return this;
    }

    public ViewHolder setImageBitmap(int viewId, Bitmap bitmap)
    {
        ImageView view = getView(viewId);
        view.setImageBitmap(bitmap);
        return this;
    }

    public ViewHolder setImageDrawable(int viewId, Drawable drawable)
    {
        ImageView view = getView(viewId);
        view.setImageDrawable(drawable);
        return this;
    }

    public ViewHolder setBackgroundColor(int viewId, int color)
    {
        View view = getView(viewId);
        view.setBackgroundColor(color);
        return this;
    }

    public ViewHolder setBackgroundRes(int viewId, int backgroundRes)
    {
        View view = getView(viewId);
        view.setBackgroundResource(backgroundRes);
        return this;
    }

    public ViewHolder setBackgroundGradient(int viewId, String color)
    {
        View view = getView(viewId);
        GradientDrawable background = (GradientDrawable) view.getBackground();
        background.setColor(Color.parseColor(color));
        return this;
    }

    public ViewHolder setTextColor(int viewId, int textColor)
    {
        TextView view = getView(viewId);
        view.setTextColor(textColor);
        return this;
    }

    public ViewHolder setTextColorRes(int viewId, int textColorRes)
    {
        TextView view = getView(viewId);
        view.setTextColor(mContext.getResources().getColor(textColorRes));
        return this;
    }

    public ViewHolder setTextSizeRes(int viewId, int textDimenRes)
    {
        TextView view = getView(viewId);
//        SystemPrintl.systemPrintl("我的字的大小是--->"+view.getTextSize());
//        SystemPrintl.systemPrintl("我的字转化--->"+CommonUtil.sp2px(mContext,15));
        //
        view.setTextSize(TypedValue.COMPLEX_UNIT_PX, mContext.getResources().getDimensionPixelSize(textDimenRes));
        return this;
    }

    @SuppressLint("NewApi")
    public ViewHolder setAlpha(int viewId, float value)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        {
            getView(viewId).setAlpha(value);
        } else
        {
            // Pre-honeycomb hack to set Alpha value
            AlphaAnimation alpha = new AlphaAnimation(value, value);
            alpha.setDuration(0);
            alpha.setFillAfter(true);
            getView(viewId).startAnimation(alpha);
        }
        return this;
    }

    public ViewHolder setVisible(int viewId, boolean visible)
    {
        View view = getView(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.GONE);
        return this;
    }
    public ViewHolder setInVisible(int viewId, boolean visible)
    {
        View view = getView(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
        return this;
    }

    public ViewHolder linkify(int viewId)
    {
        TextView view = getView(viewId);
        Linkify.addLinks(view, Linkify.ALL);
        return this;
    }

    public ViewHolder setTypeface(Typeface typeface, int... viewIds)
    {
        for (int viewId : viewIds)
        {
            TextView view = getView(viewId);
            view.setTypeface(typeface);
            view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
        return this;
    }

    public ViewHolder setProgress(int viewId, int progress)
    {
        ProgressBar view = getView(viewId);
        view.setProgress(progress);
        return this;
    }

    public ViewHolder setProgress(int viewId, int progress, int max)
    {
        ProgressBar view = getView(viewId);
        view.setMax(max);
        view.setProgress(progress);
        return this;
    }

    public ViewHolder setMax(int viewId, int max)
    {
        ProgressBar view = getView(viewId);
        view.setMax(max);
        return this;
    }

    public ViewHolder setRating(int viewId, float rating)
    {
        RatingBar view = getView(viewId);
        view.setRating(rating);
        return this;
    }

    public ViewHolder setRating(int viewId, float rating, int max)
    {
        RatingBar view = getView(viewId);
        view.setMax(max);
        view.setRating(rating);
        return this;
    }

    public ViewHolder setTag(int viewId, Object tag)
    {
        View view = getView(viewId);
        view.setTag(tag);
        return this;
    }

    public ViewHolder setTag(int viewId, int key, Object tag)
    {
        View view = getView(viewId);
        view.setTag(key, tag);
        return this;
    }

    public ViewHolder setChecked(int viewId, boolean checked)
    {
        Checkable view = (Checkable) getView(viewId);
        view.setChecked(checked);
        return this;
    }

    public ViewHolder setImage(int viewId, String imgPath, DisplayImageOptions options)
    {
        ImageView view = (ImageView) getView(viewId);

        if(options == null)  options = OptionImageUtils.getDelfaultOption();
        ImageLoader.getInstance().displayImage(imgPath,view,options);

        return this;
    }

    public ViewHolder setImageState(int viewId, String imgPath, DisplayImageOptions options)
    {
        ImageView view = (ImageView) getView(viewId);

        if(options == null)  options = OptionImageUtils.getDelfaultOption();
        ImageLoader.getInstance().displayImage(imgPath, view, options, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                view.setVisibility((CommonUtil.isRequestStr(imageUri))?View.VISIBLE:View.GONE);
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                view.setVisibility((loadedImage != null)?View.VISIBLE:View.GONE);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
            }
        });

        return this;
    }

    /**
     * 关于事件的
     */
    public ViewHolder setOnClickListener(int viewId,
                                         View.OnClickListener listener)
    {
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }

    public ViewHolder setOnTouchListener(int viewId,
                                         View.OnTouchListener listener)
    {
        View view = getView(viewId);
        view.setOnTouchListener(listener);
        return this;
    }

    public ViewHolder setOnLongClickListener(int viewId,
                                             View.OnLongClickListener listener)
    {
        View view = getView(viewId);
        view.setOnLongClickListener(listener);
        return this;
    }


}
